<template>
  <div class="home-breadNav">
    <Breadcrumb>
      <BreadcrumbItem
        v-for="item in breadArr"
        :key="item.name">{{item.title}}</BreadcrumbItem>
    </Breadcrumb>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import { homeMenuList } from 'common/js/modules'

export default {
  created () {
    this.initBread(this.routeInfo)
  },
  computed: {
    ...mapState([
      'routeInfo'
    ])
  },
  watch: {
    routeInfo (newRoute) {
      this.initBread(newRoute)
    }
  },
  data () {
    return {
      breadArr: []
    }
  },
  methods: {
    initBread (newRoute) {
      this.breadArr = [
        {
          name: 'home',
          title: '首页'
        }
      ]

      const { needOpen } = newRoute.meta

      if (needOpen) {
        const menuItem = homeMenuList.find(item => item.name === needOpen)
        this.breadArr.push({
          name: needOpen,
          title: menuItem.title
        })

        menuItem.children.map(item => {
          if (item.children) {
            const index = item.children.findIndex(itemChild => itemChild.name === newRoute.name)
            if (index > -1) {
              this.breadArr.push({
                name: item.name,
                title: item.title
              })

              this.breadArr.push({
                name: item.children[index].name,
                title: item.children[index].title
              })
            }
          } else {
            if (item.name === newRoute.name) {
              this.breadArr.push({
                name: newRoute.name,
                title: item.title
              })
            }
          }
        })
      } else {
        const menuItem = homeMenuList.find(item => item.name === newRoute.name)
        this.breadArr.push({
          name: newRoute.name,
          title: menuItem.title
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
  .home-breadNav {
    margin-top: 7px;
    cursor: default;
  }
</style>
